<!--  -->
<script setup>
import { onMounted, reactive, ref } from "vue";
import TopButton from "@/components/Pengyq/TopButton.vue";
import { useRoute } from "vue-router";
import { debounce } from "@/utils/debounce"
import { showDialog } from 'vant';
import {
    updateShopCommodityAPI,
    shopCommodityImageUp,
} from "@/server/api/shopCommodity";

import { selectShopInfoByCommodityId } from '@/server/api/shopApi.js'
import router from "@/router";
import { ToastFun } from "@/hook/toast";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
let commodityId = ref();
let swiperImg = ref([]); //图片展示
let initialReq = ref({});
// 商品信息表单数据
const updateShopCommodityReq = ref({
    avatarImag: "",
    commodityImgList: [],
    deleteImageList: [],
    commodityName: "",
    commodityDetail: "",
    price: null,
    shopId: "",
    validityTime: null,
    residue: "",
    reservationInformation: "",
});

// 获取商品信息的函数
const getCommodit = async (id) => {
    try {
        const res = await selectShopInfoByCommodityId(id);
        // 如果接口返回成功并且数据存在
        if (res && res.data.code == 200) {
            const data = res.data.data
            initialReq.value = JSON.parse(JSON.stringify(data));
            // 如果商品图片列表不为空，将图片放入swiperImg中
            const transformedImages = data.commodityImgList1.map(url => ({ url }));
            swiperImg.value = transformedImages;
            updateShopCommodityReq.value.commodityImgList = data.commodityImgListCode
            // 给表单字段赋值
            updateShopCommodityReq.value.commodityName = data.commodityName
            updateShopCommodityReq.value.commodityDetail = data.commodityDetail
            updateShopCommodityReq.value.price = data.price
            updateShopCommodityReq.value.shopId = data.shopId
            updateShopCommodityReq.value.reservationInformation = data.reservationInformation
            updateShopCommodityReq.value.residue = data.residue
            updateShopCommodityReq.value.validityTime = data.validityTime

        } else {
            ToastFun("fail", { msg: "" });
        }
    } catch (error) {
        console.error("获取商品信息失败:", error);
    }
};
const findDeletedImages = () => {
    // 找出shopFormReq.value中删除的图片ID
    const deletedImages = [];
    // 比较 shopImagListCode（数组）
    const initialImages = initialReq.value.commodityImgListCode || [];
    const updatedImages = updateShopCommodityReq.value.commodityImgList || [];
    // 找到 initialReq 中有但 updateShopCommodityReq 中没有的图片
    initialImages.forEach(imageId => {
        if (!updatedImages.includes(imageId)) {
            deletedImages.push(imageId);
        }
    });
    return deletedImages;
};
// 定义发布方法
const updateShopCommodityFun = async () => {
    updateShopCommodityReq.value.commodityId = commodityId.value;
    const uploadPromises = shopComImgListFiles.value.map(async (file) => {
        // 标记为正在上传状态
        file.status = 'uploading';
        file.message = '上传中...';

        const formData = new FormData();
        formData.append("file", file.file);

        try {
            const { data } = await shopCommodityImageUp(formData);

            if (data.code === 500) {
                // 上传失败，显示错误信息
                showDialog({
                    title: '提示',
                    message: `${data.msg}`,
                }).then(() => { });
                file.status = 'failed';
                file.message = '上传失败';
                swiperImg.value = swiperImg.value.filter(item => item !== file);
                return;
            }

            if (data.code === 200) {
                if (!Array.isArray(updateShopCommodityReq.value.commodityImgList)) {
                    updateShopCommodityReq.value.commodityImgList = [];
                }

                const newImages = data.data;

                // 检查是否存在重复图片
                const uniqueImages = newImages.filter(img =>
                    !updateShopCommodityReq.value.commodityImgList.includes(img)
                );

                if (uniqueImages.length) {
                    updateShopCommodityReq.value.commodityImgList.push(...uniqueImages);
                    file.status = 'success';
                    file.message = '上传成功';
                    file.upPath = uniqueImages[0]
                } else {
                    // 如果图片已存在
                    showDialog({
                        title: '提示',
                        message: '图片已存在',
                    }).then(() => { });
                    file.status = 'failed';
                    file.message = '图片已存在';
                    swiperImg.value = swiperImg.value.filter(item => item !== file);
                }
            }
        } catch (error) {
            console.error("上传图片异常:", error);
            file.status = 'failed';
            file.message = '上传异常';
            swiperImg.value = swiperImg.value.filter(item => item !== file);
        }
    });

    try {
        await Promise.all(uploadPromises); // 等待所有上传请求完成
    } catch (error) {
        console.error("批量上传异常:", error);
    }
    // 处理删除图片
    const deletedImages = findDeletedImages();
    if (deletedImages.length > 0) {
        updateShopCommodityReq.value.deleteImageList = deletedImages;
    }
    ToastFun("Loading", { duration: 1000 });
    let { data } = await updateShopCommodityAPI(updateShopCommodityReq.value);

    if (data.code == 200) {
        ToastFun("", {});
        window.history.back();
    } else {
        ToastFun("", {});
    }
};

const debouncedIssueShopCommodityFun = debounce(updateShopCommodityFun, 1000);

const handlePublish = async (form) => {
    form.validate().then(() => {
        if (swiperImg.value.length === 0) {
            ToastFun("show", { msg:  t("me.PersonalPosting.shop.imgTips5") });
            // ToastFun("show", { msg: t("me.PersonalPosting.uploadImage") });
            return;
        }
        debouncedIssueShopCommodityFun();
    }).catch(() => {
        ToastFun("show", { msg: t('me.PersonalPosting.rules') });
        // ToastFun("show", { msg: t("me.PersonalPosting.fillAllFields") });
    });
};


//清空按钮
const goReturn = () => {
    swiperImg.value = [];
    getCommodit(route.query.id)
    ToastFun(t("pay.success2"), {})
};

let shopComImgListFiles = ref([]);
const shopComImgUpFun = async (files) => {
    if (!Array.isArray(files)) {
        files = [files];
        shopComImgListFiles.value.push(...files);
    }
    else {
        shopComImgListFiles.value.push(...files);
    }
};

const deleteImagsLis = (file, detail) => {
    shopComImgListFiles.value = shopComImgListFiles.value.filter(item => item.objectUrl !== file.objectUrl)
    if (file.url) {
        const index = detail.index;
        if (index >= 0 && index < updateShopCommodityReq.value.commodityImgList.length) {
            if (Array.isArray(updateShopCommodityReq.value.commodityImgList)) {
                updateShopCommodityReq.value.commodityImgList.splice(index, 1);
            }

        } else {
            console.warn("无效的索引:", index);
        }
    } else {
        updateShopCommodityReq.value.commodityImgList = updateShopCommodityReq.value.commodityImgList.filter(item => item !== file.upPath)
    }
};

// 图片上传大小限制方法
const onOversize = () => {
    ToastFun("show", {
        msg: t("upTip"),
    });
};

const validateNonNegative = (field) => {
    if (updateShopCommodityReq.value[field] < 0) {
        updateShopCommodityReq.value[field] = 0; // 强制将负数改为0
    }
};
const validatorNumber = (value) => {
    return value > 0
}




onMounted(() => {
    commodityId.value = route.query.id;
    getCommodit(route.query.id)
});
</script>

<template>
    <!-- 顶部返回按钮 -->
    <TopButton title="修改商品信息" />
    <div class="UpdateItem">
        <div class="text_main">
            <textarea cols="22" rows="6" disabled :placeholder="$t('me.PersonalPosting.shop.imgTips3')"
                style="background-color: #fff" />

            <div class="perSonal_content">
                <div class="file">
                    <van-uploader :after-read="shopComImgUpFun" :max-size="5000 * 1024" @oversize="onOversize"
                        preview-size="50rem" v-model="swiperImg" :max-count="8" multiple @delete="deleteImagsLis" />
                </div>
            </div>
        </div>


        <van-form ref="form">
            <van-cell-group style="width: 370rem" inset>
                <!-- 通过 pattern 进行正则校验 -->
                <van-field :label="$t('me.PersonalPosting.subTitle')" name="pattern" disabled />
                <!-- 通过 validator 进行函数校验 -->
                <van-field :placeholder="$t('me.PersonalPosting.item.tips3')"
                    v-model.number="updateShopCommodityReq.price" :label="$t('me.PersonalPosting.price')"
                    :rules="[{ required: true, validator: validatorNumber, message: $t('me.PersonalPosting.item.tips3') }]"
                    type="number" @input="validateNonNegative('price')" />

                <!-- 有效期 -->
                <van-field v-model.number="updateShopCommodityReq.validityTime" :label="$t('me.PersonalPosting.date')"
                    name="validator" :placeholder="$t('me.PersonalPosting.dateTips')" type="number"
                    :rules="[{ required: true, validator: validatorNumber, message: $t('me.PersonalPosting.rules') }]"
                    @input="validateNonNegative('validityTime')" />

                <!-- 商品详情 -->
                <van-field v-model="updateShopCommodityReq.commodityDetail" :label="$t('me.PersonalPosting.details')"
                    name="validator" :placeholder="$t('me.PersonalPosting.detailsTips')"
                    :rules="[{ required: true, message: $t('me.PersonalPosting.rules') }]" />

                <!-- 库存 -->
                <van-field v-model.number="updateShopCommodityReq.residue" :label="$t('me.PersonalPosting.inventory')"
                    name="validator" :placeholder="$t('me.PersonalPosting.inventoryTips')" type="number"
                    @input="validateNonNegative('residue')"
                    :rules="[{ required: true, validator: validatorNumber, message: $t('me.PersonalPosting.rules') }]" />

                <!-- 注意事项 -->
                <van-field name="validator" :label="$t('me.PersonalPosting.note')"
                    v-model="updateShopCommodityReq.reservationInformation"
                    :placeholder="$t('me.PersonalPosting.noteTips')"
                    :rules="[{ required: true, message: $t('me.PersonalPosting.rules') }]" />

                <!-- 商品名 -->
                <van-field name="asyncValidator" :label="$t('me.PersonalPosting.itemName')"
                    v-model="updateShopCommodityReq.commodityName" :placeholder="$t('me.PersonalPosting.itemNameTips')"
                    :rules="[
                        {
                            required: true,
                            message: $t('me.PersonalPosting.rules'),
                        },
                    ]" />
            </van-cell-group>

            <footer>
                <div class="footer_button">
                    <button @click="goReturn">
                        {{ $t("me.PersonalPosting.reset") }}
                    </button>

                    <button @click="handlePublish($refs.form)">
                        {{ $t("me.PersonalPosting.confirm") }}
                    </button>
                </div>
            </footer>
        </van-form>
    </div>
</template>

<style scoped lang="scss">
.UpdateItem {
    overflow: hidden;
    font-size: 14rem;
    background-color: #f5f5f5;
    padding: 80rem 10rem 0 10rem;
    width: 100%;
    box-sizing: border-box;
    min-height: 100vh;

    .text_main {
        position: relative;
        width: 100%;

        textarea {
            border-radius: 10rem;
            resize: none;
            padding: 10rem;
            border: 0;
            width: 100%;
            box-sizing: border-box;
            text-indent: 1em;
        }

        .perSonal_content {
            position: absolute;
            bottom: 10rem;
            left: 10rem;
            border-radius: 6rem;
            padding: 10rem 2rem 2rem 10rem;
            text-align: center;
            background-color: #e0e0e0;
            color: #fff;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    }

    .addressCoe {
        :deep(.van-cell-group--inset) {
            margin: 0;
            position: relative;
            margin-top: 10rem;
        }

        :deep(.van-button) {
            background-color: #642e8eff;
            color: #fff;
            border-radius: 10rem;
        }

        .van-popup--bottom {
            position: relative;
            overflow: auto;

            footer {
                position: relative;
                bottom: 0rem;
                left: 10rem;
                width: 90%;
                height: 50rem;
                display: flex;
                justify-content: center;
                color: #642e8eff;
                border: 2rem solid;
                border-radius: 10rem;
                font-size: 18rem;
                align-items: center;

                .icon {
                    margin-right: 10rem;
                    width: 25rem;
                    height: 25rem;
                    text-align: center;
                    line-height: 25rem;
                    border: 2rem solid;
                    color: #642e8eff;
                    border-radius: 50%;
                    font-size: 20rem;
                }
            }
        }
    }

    .van-form {
        :deep(.van-cell__title) {
            min-width: 95rem;
        }

        .van-cell-group--inset {
            margin: 0;
            margin-top: 10rem;
        }
    }

    footer {
        width: 100%;
        position: absolute;
        bottom: -30rem;
        left: 0;

        .footer_button {
            width: 100%;
            display: flex;
            justify-content: space-around;
            padding-bottom: 16rem;
            position: fixed;
            bottom: 0;

            button {
                color: #fff;
                background-color: #642e8eff;
                width: 40%;
                height: 40rem;
                line-height: 40rem;
                border-radius: 20rem;
                text-align: center;
                border: 1rem solid;

                &:hover {
                    color: #fff;
                    background-color: #642e8eff;
                }
            }
        }
    }
}
</style>